package com.samxcode.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Given a collection of numbers that might contain duplicates, return all possible unique
 * permutations.
 * 
 * For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1].
 * 
 * Solution: 
 * 先将数组排序，然后通过比较相邻元素，略过相同的元素。其余类似于permutations
 * 
 * @author Sam
 *
 */
public class Permutations2 {

    public static List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        helper(res, new boolean[nums.length], new ArrayList<>(), nums);
        return res;
    }
    
    public static void helper(List<List<Integer>> res, boolean[] used, List<Integer> item, int[] nums) {
        if (item.size() == nums.length) {
            res.add(new ArrayList<Integer>(item));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && !used[i - 1] && nums[i] == nums[i - 1])
                continue;
            if (!used[i]) {
                used[i] = true;
                item.add(nums[i]);
                helper(res, used, item, nums);
                item.remove(item.size() - 1);
                used[i] = false;
            }
        }
    }
}
